package com.liu.queue;

import com.liu.queue.codec.MessageCodec;
import com.liu.queue.handler.PullOrdinaryRequestHandler;
import com.liu.queue.handler.PushOrdinaryRequestHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @param
 * @BelongsProject: QueueDemo2
 * @BelongsPackage: com.liu.queue
 * @author: L
 * @Date: 2023/10/22 1:13
 * @return
 */
@Slf4j
public class TcpServerInitializer extends ChannelInitializer<NioSocketChannel> {
    @Override
    protected void initChannel(NioSocketChannel ch) throws Exception {
        InetSocketAddress inetSocketAddress = ch.localAddress();
        int port = inetSocketAddress.getPort();

        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.INFO);
        ChannelPipeline pipeline = ch.pipeline();
        if (port == 9111) {
            log.info("Push");
            pipeline.addLast(new LengthFieldBasedFrameDecoder(2048, 19, 4, 0, 0));
            pipeline.addLast(loggingHandler);
            pipeline.addLast(new MessageCodec());
            pipeline.addLast(new PushOrdinaryRequestHandler());
        } else {
            log.info("Pull");
            pipeline.addLast(new HttpRequestDecoder());
            pipeline.addLast(new HttpObjectAggregator(512 * 1024));
            pipeline.addLast(new HttpResponseEncoder());
            pipeline.addLast(loggingHandler);
            pipeline.addLast(new PullOrdinaryRequestHandler());
        }


    }
}
